//
//  Network.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/7/5.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "Network.h"
#import "CommonCrypto/CommonDigest.h"//MD5加密

@implementation Network

 static NSString *const BaseURLString = @"http://120.76.162.124:8077/api/Member/";

+ (instancetype)request {
    return [[self alloc] init];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.operationManager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseURLString]];
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{

            self.operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            self.operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        });
    }
    return self;
}


- (void)GETMenthodName:(NSString *)MenthodNameString
 parameters:(NSDictionary*)parameters
    success:(void (^)(id object))success
    failure:(void (^)(NSError *error))failure{
    
    self.operationQueue = self.operationManager.operationQueue;
    self.operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [self.operationManager GET:[NSString stringWithFormat:@"%@%@",BaseURLString, MenthodNameString] parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id object = [self toArrayOrNSDictionary:responseObject];
        
        NSLog(@"GET 请求成功 : %@", object);
        success(object);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"[Network]: 请求失败 %@",error.localizedDescription);
        failure(error);
    }];
}

- (void)POSTMenthodName:(NSString *)MenthodNameString
  parameters:(NSDictionary*)parameters
     success:(void (^)(id object))success
     failure:(void (^)(NSError *error))failure{
    self.operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self.operationManager POST:[NSString stringWithFormat:@"%@%@", BaseURLString, MenthodNameString] parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id object = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"[Network]:POST 请求成功 %@",object);
        success(object);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败 %@", error.description);
        failure(error);
    }];
}

//登录 网络请求
- (void)loginWithparameters:(NSDictionary*)parameters
                     success:(void (^)(id object))success
                     failure:(void (^)(NSError *error))failure{
    
    self.operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self.operationManager GET:[NSString stringWithFormat:@"%@GetMember/AppUserLogin", BaseURLString] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id object = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"[Network]:POST 请求成功 %@",object);
        success(object);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败 %@", error.description);
        failure(error);
    }];
}

/**
 *  字典转Json转义字符串
 */
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *hasNStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *endeStr = [hasNStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    endeStr = [endeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return endeStr;
}
/**
 *  字符串转字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json字典解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}
/**
 *  字符串转数组
 */
+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json数组解析失败：%@",err);
        
        return nil;
        
    }
    
    return arr;
}
/**
 *  返回数据反序列化
 */
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}


- (void)cancelAllOperations{
    [self.operationQueue cancelAllOperations];
}


@end
